<template>
  <div>
    <div class="searchbox">
      <div class="locationbox" @click="gotolink('/setuserlocation')">
        <icon-svg
          icon-class="dingwei_blue"
          icon-color="#304056"
          class="dingweiicon"
        ></icon-svg>
        <div style="font-size: 16px">{{ usercity }}</div>
      </div>
      <van-search
        v-model="keywords"
        shape="round"
        placeholder="场馆搜索"
        class="search"
        @update:model-value="searchclub"
      >
      </van-search>
    </div>
    <van-tabs v-model:active="active" class="tabbox">
      <van-tab name="near" title="附近">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            :immediate-check="false"
            @load="onLoad"
          >
            <div
              v-for="(item, index) in currentinfo"
              :key="index"
              class="storelist"
            >
              <div class="storecard">
                <img
                  v-lazy="item.storecover_image[0]"
                  alt=""
                  class="storeimg"
                />
                <div>
                  <div class="namebox">
                    <div class="store_name">{{ item.store_name }}</div>
                    <div class="store_score">评分：4.2</div>
                  </div>
                  <div class="addressbox">
                    <div class="position">地址：{{ item.address }}</div>
                    <div class="distance" v-if="item.distance">
                      距离：{{ metertokm(item.distance) }}km
                    </div>
                  </div>
                  <div class="tagbox">
                    <van-tag round type="success" class="statustag">
                      营业中
                    </van-tag>
                    <div class="linktag" @click="gettable(item)">查看详情></div>
                  </div>
                </div>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      <van-tab name="popular" title="人气">人气</van-tab>
      <van-tab name="collect" title="我的收藏">我的收藏</van-tab>
    </van-tabs>
  </div>
</template>
<script>
import {
  getallstoreinfobylocation,
  getallstoreinfobycity,
} from "@/http/request.js";
import { showToast, showConfirmDialog } from "vant";
import { useStore } from "@/store/index.js";
export default {
  data() {
    return {
      storeinfo: [],
      currentinfo: [],
      currentpage: 1,
      allpages: 0,
      keywords: "",
      loading: false,
      finished: false,
      refreshing: false,
      usercity: "",
      locations: {},
      active: "near",
    };
  },

  methods: {
    //判断用户目前授予的信息
    gotolink(path) {
      this.$router.push(path);
    },
    async inituserinfo() {
      const store = useStore();
      const userinfo = store.getUserStoreinfo;
      var timestamp = store.getStoreTimestamp;
      if (timestamp == undefined) {
        timestamp = "";
      }
      await this.getcity();
      this.locations = userinfo.locations;
      if (this.locations == null) {
        if (this.usercity == "") {
          showConfirmDialog({
            message: "您暂未提供准确位置信息，是否提供？",
          })
            .then(() => {
              this.$router.push("./setuserlocation");
            })
            .catch(() => {
              //用户什么都不提供,根据ip获取门店信息
              this.initstorebycity(timestamp, this.usercity);
            });
        } else {
          //提供城市信息
          this.initstorebycity(timestamp, this.usercity);
        }
      } else {
        //提供经纬度信息
        const location = this.locations.lat + "," + this.locations.lng;
        this.initstorebypos(location);
      }
    },
    getcity() {
      const store = useStore();
      const userinfo = store.getUserStoreinfo;
      if (
        userinfo !== null &&
        userinfo !== undefined &&
        (userinfo.city != null || userinfo.currentcity != null)
      ) {
        if (userinfo.currentcity == null || userinfo.currentcity == undefined) {
          const addressArray = userinfo.city.split("/");
          const proWithSuffix = addressArray[0];
          const cityWithSuffix = addressArray[1];
          this.usercity = proWithSuffix + "/" + cityWithSuffix;
        } else {
          const addressArray = userinfo.currentcity.split("/");
          const proWithSuffix = addressArray[0];
          const cityWithSuffix = addressArray[1];
          this.usercity = proWithSuffix + "/" + cityWithSuffix;
        }
      } else {
        this.usercity = "";
      }
    },
    jsontoArr(data) {
      const storeinfo = Object.keys(data).map((store_id) => ({
        store_id: parseInt(store_id),
        ...data[store_id],
      }));
      for (var i = 0; i < storeinfo.length; i++) {
        const jsonString = storeinfo[i].storecover_image.replace(/'/g, '"');
        storeinfo[i].storecover_image = JSON.parse(jsonString);
        const jsonString1 = storeinfo[i].storedescribe_image.replace(/'/g, '"');
        storeinfo[i].storedescribe_image = JSON.parse(jsonString1);
      }
      return storeinfo;
    },
    initstorebycity(timestamp, city) {
      getallstoreinfobycity({
        timestamp: timestamp,
        city: city,
      }).then(async (res) => {
        this.currentinfo = [];
        this.storeinfo = [];
        const store = useStore();
        if (res.code == 0) {
          if (res.data == null) {
            showToast("暂无俱乐部");
          } else {
            this.storeinfo = await this.jsontoArr(res.data.stores_info);
            this.allpages = Math.ceil(this.storeinfo.length / 5);
            this.currentinfo = this.storeinfo.slice(0, 5);
            store.setStoreinfo(this.storeinfo);
            store.setStoreCityName(res.data.city);
            store.setStoreTimestamp(res.data.timestamp);
          }
        } else if (res.code == 1) {
          this.storeinfo = await store.getStoreinfo;
          this.allpages = Math.ceil(this.storeinfo.length / 5);
          this.currentinfo = this.storeinfo.slice(0, 5);
        } else {
          showToast(res.msg);
        }
      });
      this.listloading = false;
    },
    initstorebypos(location) {
      getallstoreinfobylocation({
        location: location,
      }).then(async (res) => {
        this.currentinfo = [];
        this.storeinfo = [];
        if (res.code == 0) {
          if (res.data.stores_info == null) {
            showToast("暂无俱乐部");
          } else {
            for (var i = 0; i < res.data.stores_info.length; i++) {
              const jsonString = res.data.stores_info[
                i
              ].storecover_image.replace(/'/g, '"');
              res.data.stores_info[i].storecover_image = JSON.parse(jsonString);
              const jsonString1 = res.data.stores_info[
                i
              ].storedescribe_image.replace(/'/g, '"');
              res.data.stores_info[i].storedescribe_image =
                JSON.parse(jsonString1);
            }
            this.storeinfo = res.data.stores_info;
            this.allpages = Math.ceil(this.storeinfo.length / 5);
            this.currentinfo = this.storeinfo.slice(0, 5);
            const store = useStore();
            store.setStoreinfo(this.storeinfo);
            store.setStoreCityName(res.data.city);
          }
        } else {
          showToast(res.msg);
        }
      });
      this.listloading = false;
    },
    metertokm(distance) {
      let kilometers = distance / 1000;
      let formattedKilometers = kilometers.toFixed(2);
      return formattedKilometers;
    },
    truncateString(str) {
      if (str !== null) {
        if (str.length <= 10) {
          return str;
        }
        return str.slice(0, 10) + "...";
      }
    },
    searchclub(value) {
      this.currentinfo = this.storeinfo.filter((store) =>
        store.store_name.includes(value)
      );
    },
    gettable(item) {
      this.$router.push({
        name: "ClubInfoPage",
        params: {
          clubinfo: JSON.stringify(item),
        },
      });
    },
    onRefresh() {
      this.finished = false;
      this.loading = true;
      this.onLoad();
    },
    onLoad() {
      setTimeout(() => {
        this.loading = false;
        this.refreshing = false;
        if (this.currentpage == this.allpages) {
          this.finished = true;
        } else {
          let startpage = this.currentpage * 5;
          let endpage = this.currentpage * 5 + 5;
          if (endpage > this.storeinfo.length) {
            endpage = this.storeinfo.length;
          }
          for (let i = startpage; i < endpage; i++) {
            this.currentinfo.push(this.storeinfo[i]);
          }
          this.currentpage += 1;
        }
      }, 1000);
    },

    getnotpayorder() {
      const store = useStore();
      let notpayorder = store.getNotPayOrder;
      if (
        notpayorder != undefined &&
        notpayorder.table != null &&
        notpayorder.table.length > 0
      ) {
        showConfirmDialog({
          title: "订单提醒",
          message: "您有未支付的订单是否去查看？有未支付订单无法进行新的球局哦",
        })
          .then(() => {
            this.$router.push("/checkout");
          })
          .catch(() => {
            this.$router.push("/homepage");
          });
      }
    },
    backlink() {
      this.$router.back();
    },
  },
  created() {
    this.inituserinfo();
    this.getnotpayorder();
  },
};
</script>
<style scoped>
.searchbox {
  display: flex;
  height: 50px;
  align-items: center;
  justify-content: space-between;
}
.locationbox {
  height: 50px;
  display: flex;
  align-items: center;
  margin-left: 5px;
}
.dingweiicon {
  width: 20px;
  height: 20px;
  margin-right: 0;
}
.search {
  flex-grow: 1;
}
.tabbox {
  width: 100%;
}
.storelist {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f2f3f5;
}
.storecard {
  width: 90%;
  border-radius: 10px;
  background-color: #ffffff;
  margin: 10px;
}
.storecard .storeimg {
  width: 100%;
  height: 200px;
  border-top-left-radius: 15px; /* 容器左上角圆角 */
  border-top-right-radius: 15px; /* 容器右上角圆角 */
}
.namebox {
  display: flex;
  justify-content: space-between;
  margin: 0 auto;
  width: 95%;
}
.namebox .store_name {
  color: black;
  font-size: 20px;
  font-weight: 550;
}
.namebox .store_score {
  color: rgb(81, 81, 81);
  font-size: 18px;
}
.addressbox {
  display: flex;
  justify-content: space-between;
  margin: 3px auto;
  width: 95%;
}
.addressbox .position {
  color: rgb(81, 81, 81);
  font-size: 17px;
}
.addressbox .distance {
  min-width: 56px;
  color: rgb(81, 81, 81);
  font-size: 17px;
}
.tagbox {
  display: flex;
  justify-content: space-between;
  margin: 3px auto;
  width: 95%;
}
.tagbox span {
  display: flex;
  justify-content: center;
}
.tagbox .statustag {
  width: 40px;
  height: 20px;
}
.tagbox .linktag {
  color: #5ea2fc;
  font-size: 16px;
}
</style>